package com.ygswglxt.user.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ygswglxt.user.entity.User;
import com.ygswglxt.user.entity.SystemConfig;
import com.ygswglxt.user.mapper.UserMapper;
import com.ygswglxt.user.mapper.SystemConfigMapper;
import com.ygswglxt.common.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserService {
    
    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private SystemConfigMapper systemConfigMapper;
    
    public Result<List<User>> getAllUsers() {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("create_time");
        // 不返回密码字段
        List<User> users = userMapper.selectList(wrapper);
        users.forEach(user -> user.setPassword(null));
        return Result.success(users);
    }
    
    // 根据ID获取用户信息
    public Result<User> getUserById(Long userId) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            return Result.error(404, "用户不存在");
        }
        // 不返回密码字段
        user.setPassword(null);
        return Result.success(user);
    }
    
    // 更新用户信息（不能修改名称）
    public Result<String> updateUserProfile(Long userId, Map<String, Object> params) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            return Result.error(404, "用户不存在");
        }
        
        // 允许修改的字段：username, password, status
        // 不允许修改：name, role, id
        if (params.containsKey("username") && StringUtils.hasText((String) params.get("username"))) {
            // 检查用户名是否已被其他用户使用
            QueryWrapper<User> wrapper = new QueryWrapper<>();
            wrapper.eq("username", params.get("username"));
            wrapper.ne("id", userId);
            Long count = userMapper.selectCount(wrapper);
            if (count > 0) {
                return Result.error("用户名已被使用");
            }
            user.setUsername((String) params.get("username"));
        }
        
        if (params.containsKey("password") && StringUtils.hasText((String) params.get("password"))) {
            user.setPassword((String) params.get("password"));
        }
        
        if (params.containsKey("status") && StringUtils.hasText((String) params.get("status"))) {
            user.setStatus((String) params.get("status"));
        }
        
        int result = userMapper.updateById(user);
        if (result > 0) {
            return Result.success("更新成功");
        } else {
            return Result.error("更新失败");
        }
    }
    
    // 获取系统配置
    public Result<Map<String, Object>> getSystemConfig() {
        try {
            List<SystemConfig> configs = systemConfigMapper.selectList(null);
            Map<String, Object> configMap = new HashMap<>();
            
            // 设置默认值
            configMap.put("workDays", 22);
            configMap.put("attendanceReminder", true);
            configMap.put("salaryReminder", true);
            
            // 从数据库读取配置
            for (SystemConfig config : configs) {
                String key = config.getConfigKey();
                String value = config.getConfigValue();
                
                if ("work_days".equals(key)) {
                    try {
                        configMap.put("workDays", Integer.parseInt(value));
                    } catch (NumberFormatException e) {
                        // 使用默认值
                    }
                } else if ("attendance_reminder".equals(key)) {
                    configMap.put("attendanceReminder", "true".equalsIgnoreCase(value));
                } else if ("salary_reminder".equals(key)) {
                    configMap.put("salaryReminder", "true".equalsIgnoreCase(value));
                }
            }
            
            return Result.success(configMap);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取系统配置失败: " + e.getMessage());
        }
    }
    
    // 更新系统配置
    public Result<String> updateSystemConfig(Map<String, Object> params) {
        try {
            // 更新工作日配置
            if (params.containsKey("workDays")) {
                updateConfig("work_days", String.valueOf(params.get("workDays")), "每月工作日数");
            }
            
            // 更新考勤提醒配置
            if (params.containsKey("attendanceReminder")) {
                updateConfig("attendance_reminder", String.valueOf(params.get("attendanceReminder")), "考勤提醒开关");
            }
            
            // 更新薪资提醒配置
            if (params.containsKey("salaryReminder")) {
                updateConfig("salary_reminder", String.valueOf(params.get("salaryReminder")), "薪资提醒开关");
            }
            
            return Result.success("配置保存成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("保存配置失败: " + e.getMessage());
        }
    }
    
    // 更新单个配置项
    private void updateConfig(String key, String value, String desc) {
        QueryWrapper<SystemConfig> wrapper = new QueryWrapper<>();
        wrapper.eq("config_key", key);
        SystemConfig config = systemConfigMapper.selectOne(wrapper);
        
        if (config == null) {
            // 如果不存在，创建新配置
            config = new SystemConfig();
            config.setConfigKey(key);
            config.setConfigValue(value);
            config.setConfigDesc(desc);
            systemConfigMapper.insert(config);
        } else {
            // 如果存在，更新配置
            config.setConfigValue(value);
            systemConfigMapper.updateById(config);
        }
    }
}

